<template>
  <page-lr>
      <el-form size="small" :model="searchForm" label-width="90px" slot="content-right">
        <el-form-item label="选择日期：">
          <el-date-picker v-model="searchForm.update_date" type="date" value-format="yyyy-MM-dd" placeholder="选择年" :picker-options="pickerDate" @change="getList"></el-date-picker>
        </el-form-item>
        <el-form-item label="国控站点：">
          <el-button v-for="(item,index) in initData.stations" :key="index" size="small" :type="searchForm.station_id == item.station_id ? 'primary' : 'default'" @click="changeType(item.station_id)">
          {{ item.name }}
        </el-button>
        </el-form-item>
      </el-form>
    <div class="list" v-loading="loading" slot="content-left">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12">
          <h3 class="align-center" style="margin-top:0">{{currentStation.city + currentStation.name}}站点源区印痕地图</h3>
          <div :style="{width:'100%',height: domHeight + 'px' ,overflow:'hidden',position:'relative',}">
            <map-box ref="mapBox" :dom-height="domHeight" :is-pronvince="true" :is-city="true" />
          </div>
        </el-col>
        <el-col :xs="24" :sm="12">
          <h3 class="align-center" style="margin-top:0">{{currentStation.city + currentStation.name}}站点印痕数据来源</h3>
          <v-chart :options="mapOptions" autoresize :style="{height:domHeight+'px', width: '100%'}"></v-chart>
        </el-col>
      </el-row>
    </div>
  </page-lr>
</template>
<script>
import cityGeoJson from '@/assets/geojson/city';
import {city} from '@/config/env';
import {geoCoordCnter} from '@/assets/js/config';
import * as echarts from 'echarts';
import {geoserver} from '@/config/env';
import mapboxgl from 'mapbox-gl';
import MapBox from '@/components/MapBox';
export default {
  components: {
    MapBox
  },
  data() {
    return {
      loading: true,
      searchForm:{
        update_date: '',
        station_id: null
      },
      initData:{
        fpDate: [],
        stations: []
      },
      pickerDate:{
        disabledDate: null
      },
      list:{
        level2: [],
        level3: []
      },
      cityGeoJson: cityGeoJson,
      currentStation: {},
      mapOptions: null,
      domHeight: null,
      url: '/station',
      map: null,
      marker: null,
    }
  },
  created() {
    this.loading = false;
    this.domHeight = document.body.clientHeight - 64 - 40 - 48*2 - 80;
    if(city == '汕头市'){
        this.url = '/air/sa'
      }
    this.getInitData();
  },
  mounted(){
    // this.initMap();
  },
  methods: {
    async getInitData(){
      this.loading = true;
      this.initData.fpDate = await this.$request('get', this.url+'/fp_dates', {});
      this.initData.stations = await this.$request('get', '/air/stations', {});
      this.loading = false;
      this.searchForm.update_date = this.$moment().format('YYYY-MM-DD');
      this.searchForm.station_id = this.initData.stations[0].station_id;
      this.pickerDate.disabledDate = (time) => {
          let len = this.initData.fpDate.length;
          const current = new Date(this.initData.fpDate[0]).getTime();
          const start = new Date(this.initData.fpDate[len-1]).getTime();
          return time.getTime() > current || time.getTime() < start;
        }
      this.map = this.$refs.mapBox.map;
      this.marker = this.$refs.mapBox.marker;
      this.getList();
    },
    changeType(val){
      this.searchForm.station_id = val;
      this.getList();
    },
    async getList(){
      this.currentStation = this.initData.stations.find(i => i.station_id === this.searchForm.station_id);       
      this.list.level2 = await this.$request('post', this.url+'/fp_region'+this.$util.serialize({...this.searchForm, level:2}), {});
      this.list.level3 = await this.$request('post', this.url+'/fp_region'+this.$util.serialize({...this.searchForm, level:3}), {});
      this.addMarker();
      this.addLayer();       
      this.initOption();
      
    },
    addMarker(){
      if (!this.map) {
        return;
      }
      if (this.marker) {
        this.marker.remove();
        this.marker = undefined;
      }
      const item = this.currentStation;
      if (item.lon && item.lat) {
        this.marker = new mapboxgl.Marker({ color: 'red'});
        this.marker.setLngLat([item.lon,item.lat]).addTo(this.map);
      }
    },
    addLayer(){
      if (!this.searchForm.update_date || !this.map) {
        return;
      }
      const url = geoserver + '/hesil/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=hesil:fp_view_test2&outputFormat=application/json&'
        + 'viewparams=station_id:' + this.searchForm.station_id
        + ';update_time:' + this.searchForm.update_date;
      // const url = geoserver + '/hesil/wms?service=WMS&version=1.1.0&request=GetMap&layers=hesil%3Afp_view_test2&bbox=112.88663752423405%2C22.21375247286299%2C116.77615489870458%2C25.64772888418747&width=768&height=678&srs=EPSG%3A404000&styles=&format=application/openlayers&viewparams=station_id:'+this.searchForm.station_id+';update_time:'+this.searchForm.update_time;
      if (!this.map.getSource('guokong-imprint')) {
        this.map.addSource('guokong-imprint', {
          type: 'geojson',
          data: url
        });
      } else {
        (this.map.getSource('guokong-imprint')).setData(url);
      }
      if (!this.map.getLayer('guokong-imprint-layer')) {
        this.map.addLayer({
          id: 'guokong-imprint-layer',
          type: 'fill',
          source: 'guokong-imprint',
          paint: {
            'fill-color': {
              property: 'conc',
              stops: [
                [0.5, 'RGB(66,1,158)'],
                [0.6, 'RGB(79,62,213)'],
                [0.8, 'RGB(67,109,244)'],
                [1, 'RGB(97,174,253)'],
                [2, 'RGB(139,224,254)'],
                [5, 'RGB(173,246,255)'],
                [8, 'RGB(191,255,255)'],
                [12, 'RGB(152,245,230)'],
                [18, 'RGB(164,221,171)'],
                [25, 'RGB(165,194,102)'],
                [35, 'RGB(189,136,50)'],
                [50, 'RGB(162,79,94)']
              ]
            }
          }
        });
      }
    },
    initOption(){
      const geoCoordMap = {...geoCoordCnter};
      const station = this.currentStation;
      const target = station ? station.name : '';
      const targetll = [station.lon, station.lat];
      const dataT = [];
      this.list.level2.forEach((d) => {
        dataT.push({
          name: d.name,
          value: d.percent,
        })
      });
      const yData = [];
      geoCoordMap[target] = targetll;
      for (let i = 0; i < dataT.length; i++) {
        yData.push(dataT[i].name);
      }
      const GZData = [];
      const tempData = [target, GZData];
      dataT.map((item, index) => {
        const arr = [];
        arr.push(item),
          arr.push({ name: target }),
          GZData.push(arr);
      });

      const convertData = (data) => {
        const res = [];
        for (let i = 0; i < data.length; i++) {
          const dataItem = data[i];
          const fromCoord = geoCoordMap[dataItem[0].name];
          const toCoord = geoCoordMap[dataItem[1].name];
          if (fromCoord && toCoord) {
            res.push({
              fromName: dataItem[0].name,
              toName: dataItem[1].name,
              coords: [fromCoord, toCoord],
              value: dataItem[0].value
            });
          }
        }
        return res;
      };
      // console.log(tempData[1],  convertData(tempData[1]));
      const barData = [];
      for (const d of this.list.level3) {
        barData.push({
          name: d.name,
          value: (d.percent * 100).toFixed(2)
        });
      }
      barData.reverse();
      const series = [];
      series.push(
        {
          name: tempData[0],
          type: 'lines',
          zlevel: 2,
          effect: {
            show: true,
            period: 4, //箭头指向速度，值越小速度越快
            trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
            symbol: 'arrow', //箭头图标
            symbolSize: 5, //图标大小
          },
          lineStyle: {
            normal: {
              width: 1, //尾迹线条宽度
              opacity: 1, //尾迹线条透明度
              curveness: .3 //尾迹线条曲直度
            }
          },
          data: convertData(tempData[1])
        },
        {
          name: tempData[0],
          type: 'scatter',
          coordinateSystem: 'geo',
          zlevel: 2,
          rippleEffect: {
            brushType: 'stroke'
          },
          label: {
            normal: {
              show: true,
              position: 'right',
              formatter: '{b}',
              fontSize: 14,
              fontFamily: 'AlibabaPuHuiTi-Bold',
            }
          },
          symbolSize: (val) => {
            return 10 + val[2] * 5;
          },
          itemStyle: {
            normal: {
              //  fontSize: 80,
            }
          },
          data: tempData[1].map((dataItem) => {
            return {
              name: dataItem[0].name,
              value: geoCoordMap[dataItem[0].name].concat([dataItem[0].value])
            };
          })
        },
        {
          type: 'effectScatter',
          coordinateSystem: 'geo',
          zlevel: 4,
          symbolSize: 16,
          label: {
            normal: {
              show: true,
              position: 'right',
              formatter: '{b}',
              fontSize: 18,
              fontWeight: 600,
              fontFamily: 'AlibabaPuHuiTi-Bold',
              // color: 'white'
            }
          },
          itemStyle: {
            normal: {
              color: 'white',
            }
          },
          rippleEffect: {
            scale: 4,
            brushType: 'stroke'
          },
          data: [{
            name: tempData[0],
            value: geoCoordMap[tempData[0]],
            visualMap: false
          }],
        },
        {
          name: 'barSer',
          type: 'bar',
          roam: false,
          zlevel: 2,
          barMaxWidth: 25,
          yAxisIndex: 1,
          itemStyle: {
            normal: {
              color: '#5470c6'
            },
          },
          label: {
            normal: {
              show: false,
              position: 'right',
              offset: [0, 10]
            },
            emphasis: {
              show: true,
              position: 'right',
              offset: [10, 0]
            }
          },
          data: barData
        },
        {
          type: 'pie',
          radius: [40, 70],
          top: '70%',
          height: '30%',
          left: '20%',
          width: 400,
          label: {
            // alignTo: 'edge',
            textStyle: {
              color: '#000',
              fontSize: 14,
              fontFamily: 'AlibabaPuHuiTi-Regular',
            },
            formatter: (params) => {
              return params.name + ':' + (params.value * 100).toFixed(2) + '%';
            },
            minMargin: 5,
            lineHeight: 15,
          },
          data: dataT
        }
      );
      echarts.registerMap('guangdong', cityGeoJson);

      this.mapOptions = {
        tooltip: {
          trigger: 'item',
          formatter: (params) => {
            if (params.seriesType == 'scatter' && params.name != tempData[0]) {
              return params.data.name + '<br />贡献量：' + (params.data.value[2] * 100).toFixed(2) + '%';
            } else if (params.seriesType == 'lines') {
              return params.data.fromName + ' ---> '
                + params.data.toName + "<br />贡献量：" + (params.data.value * 100).toFixed(2) + '%';
            } else {
              return params.name;
            }
          }
        },
        visualMap: {
          type: 'continuous',
          text: ['', ''],
          showLabel: false,
          seriesIndex: [0],
          min: dataT[0].value,
          max: dataT[dataT.length - 1].value,
          show: false,
          color: ['#f44336', '#fc9700', '#ffde00', '#ffde00', '#00eaff'],
          textStyle: {
            color: '#000'
          },
          bottom: 30,
        },
        grid: {
          right: 20,
          top: 20,
          bottom: 20,
          width: '10%'
        },
        xAxis: {
          type: 'value',
          min: 0,
          max: 100,
          splitNumber: 2,
          scale: true,
          position: 'top',
          boundaryGap: false,
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            margin: 0,
            textStyle: {
              color: '#000',
              fontSize: 14,
              fontFamily: 'AlibabaPuHuiTi-Bold',
            },
            formatter: (value) => {
              return value + '%';
            }
          }
        },
        yAxis: [
          {
            type: 'category',
            nameGap: 16,
            axisLine: {
              show: false,
              lineStyle: {
                color: '#ddd'
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: '#ddd'
              }
            },
            axisLabel: {
              show: false,
              interval: 0,
              textStyle: {
                color: '#999'
              }
            },
            data: yData
          },
          {
            type: 'category',
            nameGap: 16,
            position: 'left',
            axisLine: {
              show: false,
              lineStyle: {
                color: '#ddd'
              }
            },
            axisTick: {
              show: false,
              lineStyle: {
                color: '#ddd'
              }
            },
            axisLabel: {
              show: true,
              // align: 'left',
              interval: 0,
              textStyle: {
                color: '#000',
                fontSize: 14,
                fontFamily: 'AlibabaPuHuiTi-Regular',
              }
            },
            data: barData.map(i => i.name)
          },
        ],
        geo: {
          map: 'guangdong',
          zoom: 0.6,
          left: 0,
          right: '20%',
          label: {
            show: true,
            fontSize: 14,
            fontFamily: 'AlibabaPuHuiTi-Regular',
          },
          roam: true, //是否允许缩放
          itemStyle: {
            normal: {
              color: 'rgba(51, 69, 89, .5)', //地图背景色
              borderColor: '#516a89', //省市边界线00fcff 516a89
              borderWidth: 1
            },
            emphasis: {
              color: 'rgba(37, 43, 61, .5)' //悬浮背景
            }
          }
        },
        series: series
      };
    }
  }
}
</script>